<template>
  <div class="bg-white rounded-lg shadow-lg p-2">
    <!-- 本章要点介绍 -->
    <div v-if="props.showChapterHighlights" class="mb-6">
      <div class="flex items-center justify-between mb-4">
        <h2 class="text-xl font-semibold text-gray-800">本章要点介绍</h2>
        <button 
          @click="toggleChapterHighlights"
          class="flex items-center space-x-2 px-3 py-1 text-sm text-gray-600 hover:text-gray-800 hover:bg-gray-100 rounded transition-colors"
        >
          <span>{{ isChapterHighlightsExpanded ? '收起' : '展开' }}</span>
          <svg 
            class="w-4 h-4 transform transition-transform duration-200" 
            :class="{ 'rotate-180': !isChapterHighlightsExpanded }"
            fill="none" 
            stroke="currentColor" 
            viewBox="0 0 24 24"
          >
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
          </svg>
        </button>
      </div>
      <div 
        class="transition-all duration-300 ease-in-out overflow-hidden"
        :class="{
          'max-h-0 opacity-0': !isChapterHighlightsExpanded,
          'max-h-screen opacity-100': isChapterHighlightsExpanded
        }"
      >
        <!-- 加载状态 -->
        <div v-if="isLoadingHighlights" class="flex items-center justify-center py-8">
          <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500"></div>
          <span class="ml-3 text-gray-600">正在加载章节要点...</span>
        </div>
        
        <!-- 错误状态 -->
        <div v-else-if="highlightsError" class="bg-red-50 border border-red-200 rounded-lg p-4">
          <div class="flex items-center">
            <svg class="w-5 h-5 text-red-500 mr-2" fill="currentColor" viewBox="0 0 20 20">
              <path fill-rule="evenodd"
                d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z"
                clip-rule="evenodd" />
            </svg>
            <span class="text-red-700">{{ highlightsError }}</span>
          </div>
        </div>
        
        <!-- 章节要点数据存在时，显示ChapterHighlights组件 -->
        <ChapterHighlights 
          v-else-if="chapterHighlightsData" 
          :chapterData="chapterHighlightsData" 
        />
        
        <!-- 当章节要点为空时，显示lightConfig配置的markdown文件 -->
        <div v-else class="light-config-section">
          <!-- 知识点配置文件显示区域 (仅在没有章节要点数据时显示) -->
          <div v-if="!chapterHighlightsData && props.lightConfig && props.lightConfig.uploadedFiles && props.lightConfig.uploadedFiles.length > 0" class="bg-amber-50 border border-amber-200 rounded-lg p-4 shadow-sm">
            <!-- <h4 class="text-lg font-semibold text-amber-800 mb-3 flex items-center">
              <svg class="w-5 h-5 mr-2 text-amber-600" fill="currentColor" viewBox="0 0 20 20">
                <path d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/>
              </svg>
              知识点配置文件
            </h4>
            <div class="mb-3">
              <span class="text-sm text-amber-700 font-medium">权重: {{ props.lightConfig.weight || 0 }}%</span>
              <span v-if="props.lightConfig.isRequired" class="ml-2 px-2 py-1 bg-red-100 text-red-700 text-xs rounded font-medium">必修</span>
              <span v-else class="ml-2 px-2 py-1 bg-green-100 text-green-700 text-xs rounded font-medium">选修</span>
            </div> -->
            
            <!-- Markdown 文件内容直接显示 (只显示第一个元素) -->
            <div v-if="lightConfigMarkdownContents.length > 0" class="markdown-contents space-y-4">
              <div 
                v-if="lightConfigMarkdownContents[0]"
                :key="lightConfigMarkdownContents[0].originalFile.path"
                class="markdown-item bg-white border border-gray-200 rounded-lg p-4"
              >
                <h5 class="text-md font-medium text-gray-800 mb-3 flex items-center">
                  <svg class="w-4 h-4 mr-2" fill="currentColor" viewBox="0 0 20 20">
                    <path fill-rule="evenodd" d="M4 4a2 2 0 012-2h4.586A2 2 0 0112 2.586L15.414 6A2 2 0 0116 7.414V16a2 2 0 01-2 2H6a2 2 0 01-2-2V4zm2 6a1 1 0 011-1h6a1 1 0 110 2H7a1 1 0 01-1-1zm1 3a1 1 0 100 2h6a1 1 0 100-2H7z" clip-rule="evenodd" />
                  </svg>
                  {{ lightConfigMarkdownContents[0].title }}
                </h5>
                
                <!-- 主要内容区域：左侧目录 + 右侧内容 -->
                <div class="flex h-96 border border-gray-200 rounded-lg bg-gray-50">
                  <!-- 左侧目录 -->
                  <div class="w-1/4 bg-gray-50 border-r border-gray-200 overflow-y-auto">
                    <div class="p-4">
                      <h4 class="text-sm font-semibold text-gray-700 mb-3">📋 目录</h4>
                      <nav class="space-y-1">
                        <div 
                          v-for="item in lightConfigMarkdownContents[0].tableOfContents" 
                          :key="item.id"
                          :class="[
                            'block px-3 py-2 text-sm rounded-md cursor-pointer transition-colors',
                            item.level === 1 ? 'font-semibold' : '',
                            item.level === 2 ? 'ml-3' : '',
                            item.level === 3 ? 'ml-6' : '',
                            item.level >= 4 ? 'ml-9' : '',
                            activeHeading === item.id 
                              ? 'bg-blue-100 text-blue-700 border-l-4 border-blue-500' 
                              : 'text-gray-600 hover:bg-gray-100 hover:text-gray-900'
                          ]"
                          @click="scrollToHeading(item.id)"
                        >
                          {{ item.text }}
                        </div>
                      </nav>
                    </div>
                  </div>
                  
                  <!-- 右侧内容 -->
                  <div 
                    ref="markdownContentRef"
                    class="flex-1 p-6 prose max-w-none text-sm overflow-y-auto bg-white"
                    @scroll="handleScroll"
                    v-html="lightConfigMarkdownContents[0].content"
                  ></div>
                </div>
              </div>
            </div>
            
            <!-- 其他类型文件列表 -->
            <div v-if="props.lightConfig.uploadedFiles.filter(f => !f.url?.endsWith('.md') && !f.path?.endsWith('.md') && !f.filename?.endsWith('.md')).length > 0" class="space-y-3">
              <div 
                v-for="(file, index) in props.lightConfig.uploadedFiles.filter(f => !f.url?.endsWith('.md') && !f.path?.endsWith('.md') && !f.filename?.endsWith('.md'))" 
                :key="index"
                class="bg-white border border-gray-200 rounded-lg p-3"
              >
                <div class="flex items-center justify-between mb-2">
                  <span class="font-medium text-gray-800">{{ file.title || `配置文件 ${index + 1}` }}</span>
                </div>
                <p v-if="file.description" class="text-sm text-gray-600 mb-2">{{ file.description }}</p>
                <div class="mt-2">
                  <button 
                    @click="loadMarkdownFile(file.url || file.path || file.filename)"
                    class="flex items-center space-x-2 px-3 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 transition-colors text-sm"
                  >
                    <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
                      <path fill-rule="evenodd" d="M4 4a2 2 0 012-2h4.586A2 2 0 0112 2.586L15.414 6A2 2 0 0116 7.414V16a2 2 0 01-2 2H6a2 2 0 01-2-2V4zm2 6a1 1 0 011-1h6a1 1 0 110 2H7a1 1 0 01-1-1zm1 3a1 1 0 100 2h6a1 1 0 100-2H7z" clip-rule="evenodd" />
                    </svg>
                    <span>查看内容</span>
                  </button>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 既没有章节要点数据，也没有知识点配置文件时的提示 -->
          <div v-else class="bg-gray-50 border border-gray-200 rounded-lg p-4 text-center">
            <svg class="w-8 h-8 text-gray-400 mx-auto mb-2" fill="currentColor" viewBox="0 0 20 20">
              <path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clip-rule="evenodd" />
            </svg>
            <span class="text-gray-600">暂无章节要点数据和知识点配置</span>
          </div>
        </div>
      </div>
    </div>
    
    <!-- Markdown文档显示区域 -->
    <div v-if="isMarkdownViewerVisible" class="border border-gray-200 rounded-lg p-6 bg-gray-50 mb-6">
      <div class="flex items-center justify-between mb-4">
        <h3 class="text-xl font-semibold text-gray-800">知识点文档</h3>
        <button @click="hideMarkdownViewer()" class="text-gray-500 hover:text-gray-700 text-sm font-medium">✕ 关闭</button>
      </div>
      <div class="bg-white rounded-lg p-6 prose max-w-none" v-html="markdownContent"></div>
    </div>
    <!-- PDF显示区域 -->
    <div v-if="isPdfViewerVisible" class="border border-gray-200 rounded-lg p-2 mb-6">
      <div class="flex items-center justify-between mb-2">
        <h5 class="text-lg font-semibold text-gray-800">PDF预览</h5>
        <button @click="hidePdfViewer()" class="text-gray-500 hover:text-gray-700 text-sm font-medium">✕ 关闭</button>
      </div>
      <div class="bg-gray-50 rounded-lg p-4">
        <div v-if="currentPdfPath" class="w-full h-[700px] overflow-auto border border-gray-300 rounded-lg">
          <VuePdfEmbed :source="currentPdfPath" class="w-full" />
        </div>
      </div>
    </div>

    <!-- DOCX文档显示区域 -->
    <div v-if="isDocxViewerVisible" class="border border-gray-200 rounded-lg p-6 bg-gray-50 mb-6">
      <div class="flex items-center justify-between mb-4">
        <h3 class="text-xl font-semibold text-gray-800">文档预览</h3>
        <button @click="hideDocxViewer()" class="text-gray-500 hover:text-gray-700 text-sm font-medium">✕ 关闭</button>
      </div>

      <!-- 加载状态 -->
      <div v-if="isLoadingDocxViewer" class="flex items-center justify-center py-8">
        <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500"></div>
        <span class="ml-3 text-gray-600">正在加载文档...</span>
      </div>

      <!-- 错误状态 -->
      <div v-else-if="docxViewerError" class="bg-red-50 border border-red-200 rounded-lg p-4">
        <div class="flex items-center">
          <svg class="w-5 h-5 text-red-500 mr-2" fill="currentColor" viewBox="0 0 20 20">
            <path fill-rule="evenodd"
              d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z"
              clip-rule="evenodd" />
          </svg>
          <span class="text-red-700">{{ docxViewerError }}</span>
        </div>
      </div>

      <!-- 文档内容 -->
      <div v-else-if="docxViewerContent">
        <div class="flex gap-4" style="height: 600px;">
          <!-- 左侧目录 -->
          <div v-if="documentOutline.length > 0" :class="[
            'bg-white rounded border transition-all duration-300 ease-in-out overflow-hidden',
            isOutlineExpanded ? 'w-1/4' : 'w-12'
          ]">
            <div class="flex items-center justify-between p-4 border-b border-gray-200">
              <h4 v-if="isOutlineExpanded" class="font-semibold text-gray-700 text-sm">文档目录</h4>
              <button @click="toggleOutline" class="p-1 rounded hover:bg-gray-100 transition-colors"
                :title="isOutlineExpanded ? '收缩目录' : '展开目录'">
                <svg class="w-4 h-4 text-gray-600 transition-transform duration-200"
                  :class="{ 'rotate-180': !isOutlineExpanded }" fill="none" stroke="currentColor"
                  viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7" />
                </svg>
              </button>
            </div>
            <div v-if="isOutlineExpanded" class="p-4 overflow-y-auto" style="height: calc(100% - 60px);">
              <nav class="space-y-1">
                <a v-for="(item, index) in documentOutline" :key="index" @click="scrollToHeading(item.id)" :class="[
                  'block text-sm cursor-pointer hover:text-blue-600 transition-colors py-1',
                  item.level === 1 ? 'font-medium text-gray-800' : '',
                  item.level === 2 ? 'text-gray-700 ml-4' : '',
                  item.level === 3 ? 'text-gray-600 ml-8' : '',
                  item.level === 4 ? 'text-gray-600 ml-12' : '',
                  item.level === 5 ? 'text-gray-600 ml-16' : '',
                  item.level === 6 ? 'text-gray-600 ml-20' : ''
                ]">
                  {{ item.text }}
                </a>
              </nav>
            </div>
            <div v-else class="flex flex-col items-center justify-center h-full py-4">
              <svg class="w-6 h-6 text-gray-400 mb-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16" />
              </svg>
              <span class="text-xs text-gray-400 writing-mode-vertical-rl text-orientation-mixed">目录</span>
            </div>
          </div>

          <!-- 右侧文档内容 -->
          <div id="docx-viewer-content" :class="[
            'bg-white rounded border overflow-y-auto transition-all duration-300 ease-in-out',
            documentOutline.length > 0 ? (isOutlineExpanded ? 'w-3/4' : 'calc(100% - 4rem)') : 'w-full'
          ]" :style="{
            width: documentOutline.length > 0 ? (isOutlineExpanded ? '75%' : 'calc(100% - 4rem)') : '100%'
          }">
            <div class="prose max-w-none p-6" v-html="docxViewerContent"></div>
          </div>
        </div>
      </div>
    </div>

    <!-- 课件资料 -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
      <div 
        v-for="(material, index) in processedMaterials" 
        :key="index"
        class="border border-gray-200 rounded-lg p-4 hover:shadow-md transition-shadow"
        :class="{ 'cursor-pointer': material.type === 'docx' && material.files && material.files.length > 0 }"
        @click="material.type === 'docx' && material.files && material.files.length > 0 ? showDocxViewer(material.files[0]) : null"
      >
        <div class="flex items-center mb-3">
          <svg class="w-8 h-8 mr-3" :class="getIconClass(material.icon)" fill="currentColor" viewBox="0 0 20 20">
            <path d="M4 3a2 2 0 00-2 2v10a2 2 0 002 2h12a2 2 0 002-2V5a2 2 0 00-2-2H4zm12 12H4l4-8 3 6 2-4 3 6z" />
          </svg>
          <h3 class="text-lg font-medium text-gray-800">{{ material.title }}</h3>
        </div>
        <p class="text-gray-600 text-sm mb-3">{{ material.description }}</p>
        
        <!-- 思维导图类型 -->
        <div v-if="material.type === 'mindmap'">
          <button class="w-full bg-purple-500 text-white py-2 px-4 rounded hover:bg-purple-600 transition-colors">
            预览图片
          </button>
        </div>
        
        <!-- PDF类型 -->
        <div v-else-if="material.type === 'pdf' && material.files" class="space-y-2">
          <div v-for="(file, fileIndex) in material.files" :key="fileIndex" class="flex space-x-2">
            <button @click.stop="showPdfViewer(file)"
              class="flex-1 bg-blue-500 text-white py-2 px-4 rounded hover:bg-blue-600 transition-colors text-sm">
              显示
            </button>
            <button @click.stop="viewPDF(file)"
              class="flex-1 bg-green-500 text-white py-2 px-4 rounded hover:bg-green-600 transition-colors text-sm">
              新窗口
            </button>
          </div>
        </div>
        
        <!-- DOCX类型 -->
        <div v-else-if="material.type === 'docx' && material.files" class="space-y-2">
          <div v-for="(file, fileIndex) in material.files" :key="fileIndex" class="flex space-x-2">
            <button @click.stop="showDocxViewer(file)"
              class="flex-1 bg-blue-500 text-white py-2 px-4 rounded hover:bg-blue-600 transition-colors text-sm">
              显示
            </button>
            <button @click.stop="downloadDocx(file)"
              class="flex-1 bg-green-500 text-white py-2 px-4 rounded hover:bg-green-600 transition-colors text-sm">
              下载
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import mammoth from 'mammoth'
import VuePdfEmbed from 'vue-pdf-embed'
import ChapterHighlights from './ChapterHighlights.vue'
import { useStudyTracker } from '@/composables/useStudyTracker'
import { useAuthStore } from '@/stores/auth'
import { marked } from 'marked'

// 从环境变量读取API基础地址
const API_BASE_URL = `http://${import.meta.env.VITE_BACKEND_HOST}:${import.meta.env.VITE_BACKEND_PORT}`
// 静态文件服务地址
const STATIC_BASE_URL = import.meta.env.VITE_STATIC_BASE_URL || `http://${import.meta.env.VITE_BACKEND_HOST}:${import.meta.env.VITE_BACKEND_PORT}/public`

// 获取学习追踪功能
const { trackMaterialClick } = useStudyTracker()

// Props定义
const props = defineProps({
  // 章节路径，用于构建材料文件路径
  chapterPath: {
    type: String,
    default: '/chap01'
  },
  // 章节编号，用于获取对应的章节数据
  chapterNumber: {
    type: Number,
    default: 1
  },
  // 材料配置
  materials: {
    type: Array,
    default: () => [
      {
        type: 'mindmap',
        title: '本章思维导图',
        description: '第1章知识点结构化思维导图',
        icon: 'purple',
        action: 'preview'
      },
      {
        type: 'pdf',
        title: '本章课件',
        description: '前端技术发展历程和基础概念介绍',
        icon: 'red',
        files: ['/第01课-绪论.pdf']
      },
      {
        type: 'docx',
        title: '本章讲义',
        description: '第1章讲义内容',
        icon: 'green',
        files: ['/第1章绪论.docx']
      }
    ]
  },
  // 是否显示章节要点
  showChapterHighlights: {
    type: Boolean,
    default: true
  },
  // lightConfig配置
  lightConfig: {
    type: [Object, null],
    default: null
  }
})

// 计算属性：处理材料文件路径
const processedMaterials = computed(() => {
  return props.materials.map(material => {
    if (material.files) {
      return {
        ...material,
        files: material.files.map(file => {
          // 如果文件路径已经是完整路径（包含章节目录），直接使用
          // 否则添加chapterPath前缀
          if (file.startsWith('chap') || file.startsWith('/chap') || file.startsWith('http')) {
            return file.startsWith('/') ? file : `/${file}`
          }
          return `${props.chapterPath}${file}`
        })
      }
    }
    return material
  })
})

// PDF相关状态
const isPdfViewerVisible = ref(false)
const currentPdfPath = ref('')
const isLoadingPdfViewer = ref(false)
const pdfViewerError = ref('')

// DOCX相关状态
const isDocxViewerVisible = ref(false)
const isLoadingDocxViewer = ref(false)
const docxViewerError = ref('')
const docxViewerContent = ref('')
const documentOutline = ref([])
const isOutlineExpanded = ref(true)

// 章节要点折叠状态
const isChapterHighlightsExpanded = ref(true)

// 章节要点数据状态
const chapterHighlightsData = ref(null)
const isLoadingHighlights = ref(false)
const highlightsError = ref('')

// markdown显示相关状态
const markdownContent = ref('')
const isMarkdownViewerVisible = ref(false)
const lightConfigMarkdownContents = ref([])
const activeHeading = ref('')
const markdownContentRef = ref(null)

const authStore = useAuthStore()

// 获取当前章节数据
const currentChapterData = computed(() => {
  return chapterHighlightsData.value || {
    title: `第${props.chapterNumber}章 学习要点`,
    leftSection: {
      title: '暂无数据',
      icon: 'lightning',
      subsections: []
    },
    rightSection: {
      title: '暂无数据', 
      icon: 'book',
      subsections: []
    },
    tip: {
      label: '提示',
      content: '章节要点数据加载中...'
    }
  }
})

// 从API获取章节要点数据
const loadChapterHighlights = async () => {
  if (!props.chapterNumber) return
  
  isLoadingHighlights.value = true
  highlightsError.value = ''
  
  try {
    const response = await fetch(`${API_BASE_URL}/api/chapter-highlights/chapter/${props.chapterNumber}`, {
      headers: {
        'Authorization': `Bearer ${authStore.token}`
      }
    })
    
    if (response.ok) {
      const result = await response.json()
      if (result.success && result.data) {
        chapterHighlightsData.value = result.data
      }
    } else if (response.status === 404) {
      // 如果没有找到对应章节的要点配置，使用默认数据
      console.log(`第${props.chapterNumber}章暂无要点配置`)
    } else {
      throw new Error('获取章节要点失败')
    }
  } catch (err) {
    console.error('加载章节要点失败:', err)
    highlightsError.value = err instanceof Error ? err.message : '加载章节要点失败'
  } finally {
    isLoadingHighlights.value = false
  }
}



// 加载并显示markdown文件
const loadMarkdownFile = async (filePath) => {
  try {
    const response = await fetch(`${STATIC_BASE_URL}/${filePath}`)
    if (response.ok) {
      const markdownText = await response.text()
      markdownContent.value = marked(markdownText)
      isMarkdownViewerVisible.value = true
    } else {
      console.error('加载markdown文件失败:', filePath)
    }
  } catch (error) {
    console.error('加载markdown文件失败:', error)
  }
}

// 关闭markdown查看器
const hideMarkdownViewer = () => {
  isMarkdownViewerVisible.value = false
  markdownContent.value = ''
}

// 跳转到指定标题
const scrollToHeading = (headingId) => {
  if (!markdownContentRef.value) return
  
  const targetElement = markdownContentRef.value.querySelector(`#${headingId}`)
  if (targetElement) {
    targetElement.scrollIntoView({ 
      behavior: 'smooth', 
      block: 'start' 
    })
    activeHeading.value = headingId
  }
}

// 监听滚动事件，高亮当前标题
const handleScroll = () => {
  if (!markdownContentRef.value) return
  
  const headings = markdownContentRef.value.querySelectorAll('h1, h2, h3, h4, h5, h6')
  const scrollTop = markdownContentRef.value.scrollTop
  
  let currentHeading = ''
  
  headings.forEach(heading => {
    const rect = heading.getBoundingClientRect()
    const containerRect = markdownContentRef.value.getBoundingClientRect()
    
    if (rect.top - containerRect.top <= 100) {
      currentHeading = heading.id
    }
  })
  
  activeHeading.value = currentHeading
}

// 生成markdown目录结构
const generateTableOfContents = (htmlContent) => {
  const parser = new DOMParser()
  const doc = parser.parseFromString(htmlContent, 'text/html')
  const headings = doc.querySelectorAll('h1, h2, h3, h4, h5, h6')
  
  const toc = []
  headings.forEach((heading, index) => {
    const level = parseInt(heading.tagName.charAt(1))
    const text = heading.textContent.trim()
    const id = `heading-${index}`
    
    // 为标题添加ID
    heading.id = id
    
    toc.push({
      id,
      text,
      level
    })
  })
  
  return {
    toc,
    htmlWithIds: doc.body.innerHTML
  }
}

// 自动加载lightConfig中的markdown文件内容
const loadLightConfigMarkdownContents = async () => {
  if (!props.lightConfig?.uploadedFiles) return
  
  lightConfigMarkdownContents.value = []
  
  for (const file of props.lightConfig.uploadedFiles) {
    const filePath = file.url || file.path || file.filename
    if (filePath && (filePath.endsWith('.md') || filePath.endsWith('.markdown'))) {
      try {
        const fullPath = filePath.startsWith('http') ? filePath : `${STATIC_BASE_URL}/${filePath}`
        const response = await fetch(fullPath)
        
        if (response.ok) {
          const markdownText = await response.text()
          const htmlContent = marked(markdownText)
          
          // 生成目录和带ID的HTML内容
          const { toc, htmlWithIds } = generateTableOfContents(htmlContent)
          
          lightConfigMarkdownContents.value.push({
            title: file.title || file.name || file.filename || filePath.split('/').pop() || '未命名文件',
            content: htmlWithIds,
            tableOfContents: toc,
            originalFile: file
          })
        } else {
          console.error('加载markdown文件失败:', filePath)
        }
      } catch (error) {
        console.error('加载markdown文件失败:', error)
      }
    }
  }
}

// 监听lightConfig变化
watch(() => props.lightConfig, () => {
  loadLightConfigMarkdownContents()
}, { immediate: true })

// 组件挂载时加载数据
onMounted(() => {
  loadChapterHighlights()
  loadLightConfigMarkdownContents()
})

// PDF相关方法
const showPdfViewer = async (path) => {
  isPdfViewerVisible.value = true
  isLoadingPdfViewer.value = true
  pdfViewerError.value = ''
  
  // 记录PDF查看行为
  const fileName = path.split('/').pop() || 'PDF文件'
  trackMaterialClick(`PDF查看: ${fileName}`, path)
  
  try {
    // 构建完整的静态文件服务地址
    const fullPath = path.startsWith('http') ? path : `${STATIC_BASE_URL}${path}`
    console.log('showPdfViewer fullPath:', fullPath)
    
    // 验证PDF文件是否可访问
    const response = await fetch(fullPath, { method: 'HEAD' })
    if (!response.ok) {
      throw new Error(`PDF文件无法访问: ${response.status} ${response.statusText}`)
    }
    
    currentPdfPath.value = fullPath
  } catch (error) {
    pdfViewerError.value = `PDF加载失败: ${error instanceof Error ? error.message : '未知错误'}`
    console.error('Error loading PDF:', error)
  } finally {
    isLoadingPdfViewer.value = false
  }
}

const hidePdfViewer = () => {
  isPdfViewerVisible.value = false
  currentPdfPath.value = ''
  isLoadingPdfViewer.value = false
  pdfViewerError.value = ''
}

const viewPDF = (path) => {
  // 构建完整的静态文件服务地址
  const fullPath = path.startsWith('http') ? path : `${STATIC_BASE_URL}${path}`
  window.open(fullPath, '_blank')
  // 记录PDF新窗口打开行为
  const fileName = path.split('/').pop() || 'PDF文件'
  trackMaterialClick(`PDF新窗口: ${fileName}`, path)
}

// DOCX相关方法
const showDocxViewer = async (path) => {
  isDocxViewerVisible.value = true
  isLoadingDocxViewer.value = true
  docxViewerError.value = ''
  
  // 记录DOCX查看行为
  const fileName = path.split('/').pop() || 'DOCX文件'
  trackMaterialClick(`DOCX查看: ${fileName}`, path)
  
  try {
    await loadDocxContent(path)
  } catch (error) {
    docxViewerError.value = `文档加载失败: ${error instanceof Error ? error.message : '未知错误'}`
    console.error('Error loading document:', error)
  } finally {
    isLoadingDocxViewer.value = false
  }
}

// 加载DOCX内容
const loadDocxContent = async (filePath) => {
  try {
    // 构建完整的静态文件服务地址
    const fullPath = filePath.startsWith('http') ? filePath : `${STATIC_BASE_URL}${filePath}`
    const response = await fetch(fullPath)
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    const arrayBuffer = await response.arrayBuffer()
    
    // 使用mammoth解析DOCX文件
    const result = await mammoth.convertToHtml({ arrayBuffer })
    
    if (result.messages && result.messages.length > 0) {
      console.warn('Mammoth conversion warnings:', result.messages)
    }
    
    docxViewerContent.value = result.value
    
    // 生成文档目录
    generateDocumentOutline(result.value)
  } catch (error) {
    throw error
  }
}

// 生成文档目录
const generateDocumentOutline = (htmlContent) => {
  const tempDiv = document.createElement('div')
  tempDiv.innerHTML = htmlContent
  const headings = tempDiv.querySelectorAll('h1, h2, h3, h4, h5, h6')
  
  documentOutline.value = Array.from(headings).map((heading, index) => {
    const level = parseInt(heading.tagName.charAt(1))
    const id = `heading-${index}`
    heading.id = id
    
    return {
      id,
      text: heading.textContent || '',
      level
    }
  })
  
  // 更新文档内容以包含ID
  docxViewerContent.value = tempDiv.innerHTML
}

const hideDocxViewer = () => {
  isDocxViewerVisible.value = false
  docxViewerContent.value = ''
  documentOutline.value = []
}

const downloadDocx = (path) => {
  // 构建完整的静态文件服务地址
  const fullPath = path.startsWith('http') ? path : `${STATIC_BASE_URL}${path}`
  const link = document.createElement('a')
  link.href = fullPath
  link.download = path.split('/').pop()
  link.click()
  
  // 记录DOCX下载行为
  const fileName = path.split('/').pop() || 'DOCX文件'
  trackMaterialClick(`DOCX下载: ${fileName}`, path)
}

const toggleOutline = () => {
  isOutlineExpanded.value = !isOutlineExpanded.value
}

// 切换章节要点展开/收起状态
const toggleChapterHighlights = () => {
  isChapterHighlightsExpanded.value = !isChapterHighlightsExpanded.value
}

// 获取图标样式类
const getIconClass = (iconColor) => {
  const colorMap = {
    purple: 'text-purple-500',
    red: 'text-red-500',
    green: 'text-green-500',
    blue: 'text-blue-500',
    yellow: 'text-yellow-500',
    gray: 'text-gray-500'
  }
  return colorMap[iconColor] || 'text-gray-500'
}
</script>